package xdu.lz.stage2_design_pattern.chapter8_guarded_suspension_pattern;


import java.util.LinkedList;
import java.util.Queue;

public class RequestQueue {

    private final Queue<Request> requestQueue = new LinkedList<>();

    public Request getRequest(){
        synchronized (requestQueue){
            //当队列为空，则一直等
            while (requestQueue.isEmpty()){
                try {
                    requestQueue.wait();
                } catch (InterruptedException e) {
                    //被打断要跳出去，但是不能poll，因为已经是空了，再poll会出异常
                    System.out.println("server在wait被中断");
                    return null;
                }
            }
            return requestQueue.poll();
        }
    }

    public void putRequest(Request request){
        synchronized (requestQueue){
            requestQueue.offer(request);
            //要去唤醒getRequest中wait状态
            requestQueue.notifyAll();
        }
    }

}
